// src/stores/user.js
import { defineStore } from 'pinia';

// 定义存储工具（示例：使用 localStorage）
const storage = {
  set: (key, value) => localStorage.setItem(key, value),
  get: (key) => localStorage.getItem(key)
};

// 定义常量
const ACCESS_TOKEN = 'ACCESS_TOKEN';
const USER_INFO = 'USER_INFO';
const ROLES = 'ROLES';
const REFRESH_TOKEN = 'REFRESH_TOKEN';

export const useUserStore = defineStore('user', {
  state: () => ({
    // refreshToken: storage.get(REFRESH_TOKEN) || '',
    token: storage.get(ACCESS_TOKEN) || '', // ✅ 初始化时读取 localStorage
    roles: [],
    refreshToken: '',
    userInfo: JSON.parse(storage.get(USER_INFO) || '{}'),
  }),
  actions: {
    setToken(token) {
      this.token = token;
      storage.set(ACCESS_TOKEN, token);
    },
    setRefreshToken(refreshToken){
      this.refreshToken = refreshToken;
      storage.set(REFRESH_TOKEN, refreshToken);
    },
    setRoles(roles) {
      this.roles = roles;
      storage.set(ROLES, JSON.stringify(roles)); // 存储数组需转为字符串
    },
    setUserInfo(info) {
      this.userInfo = info;
      storage.set(USER_INFO, JSON.stringify(info));
    }
  }
});